package luogu.bfs;
//P2895 [USACO08FEB]Meteor Shower S

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import java.util.Scanner;

/**
 * @author :chenjie
 * @date :Created 2022/12/24 17:02
 */
public class MeteorShowerS {
    static class Pall{
        int x;
        int y;
        int t;

        public Pall(int x, int y, int t) {
            this.x = x;
            this.y = y;
            this.t = t;
        }
    }
    static int n;
    static int[][]arr=new int[310][310];
    static boolean[][]st=new boolean[310][310];
    static int[]dx={0,0,1,-1};
    static int[]dy={1,-1,0,0};
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        n=sc.nextInt();
        for (int i = 0; i < 300; i++) {
            Arrays.fill(arr[i], -1);
        }
        for (int i = 0; i < n; i++) {
            int x=sc.nextInt();
            int y=sc.nextInt();
            int t=sc.nextInt();
            if(arr[x][y]==-1){
                arr[x][y]=t;
            }else {
                arr[x][y]=Math.min(arr[x][y],t);
            }
            for (int j = 0; j < 4; j++) {
                int a=x+dx[j],b=y+dy[j];
                if(a>=0&&b>=0){
                    if(arr[a][b]!=-1&&arr[a][b]<=t){
                        continue;
                    }
                    arr[a][b]=t;
                }
            }
        }
//        for (int i = 0; i <20; i++) {
//            System.out.println(Arrays.toString(arr[i]));
//        }
        System.out.println(bfs());

    }
    public static int bfs(){
        Queue<Pall> queue=new ArrayDeque<>();
        queue.add(new Pall(0,0,0));
        while (!queue.isEmpty()){
            Pall d = queue.remove();
            if(arr[d.x][d.y]== -1){
//                System.out.println(d.x+"  "+d.y);
                return d.t;
            }
            for (int i = 0; i < 4; i++) {
                int a=d.x+dx[i],b=d.y+dy[i];
                if(a>=0&&b>=0&&!st[a][b]){
                    if(arr[a][b]!= -1&&d.t+1>=arr[a][b]){
                        continue;
                    }
                    st[a][b]=true;
                    queue.add(new Pall(a,b,d.t+1));
                }
            }

        }
        return -1;
    }
}
